package com.mairuide._frame.config;

import com.google.gson.Gson;
import com.mairuide._frame.base.BaseController;
import com.mairuide._frame.utils.Config;
import com.mairuide._frame.utils.MD5;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide.casemanage.pojo.CaseManage;
import com.mairuide.casemanage.service.CaseManageService;
import com.mairuide.menuinfo.MenuInfo;
import com.mairuide.menuinfo.MenuInfoService;
import com.mairuide.platrole.PlatRole;
import com.mairuide.platrole.PlatRoleService;
import com.mairuide.platroleuser.PlatRoleUser;
import com.mairuide.platroleuser.PlatRoleUserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.*;

@Controller
public class LoginController extends BaseController {
	private final static String SECRET = "yxzn2018";

	@Resource
	private PlatRoleService platRoleService;
	
	@Resource
	private PlatRoleUserService platRoleUserService;

	@Resource
	private Config globalConfig;

	@Resource
	private MenuInfoService menuInfoService;
	@Resource
	private CaseManageService caseManageService;



	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(ModelMap model) throws Exception{
        return "login";
	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(ModelMap model,HttpServletRequest request) throws Exception{
		request.getSession().removeAttribute("loginUser");
		request.getSession().removeAttribute("firstLevelMenuList");
		request.getSession().removeAttribute("secondLevelMenuMap");
		request.getSession().removeAttribute("thirdLevelMenuMap");
		request.getSession().removeAttribute("parentMenuCodeMap");
		return "redirect:/login";
	}

	/**
	 * 到首页
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/home")
	public String home(ModelMap model,String caseid,String menuCode,String menuCode2) throws ParseException {
		LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// 查询用户的角色
		fillLoginUserRoleName(loginUser);
		request.getSession().setAttribute("loginUser", loginUser.getPlatManager());
		// 设置登录用户的菜单权限
		model.addAttribute("caseid",caseid==null?"":caseid);
		model.addAttribute("menuCode",menuCode==null?"":menuCode);
		model.addAttribute("menuCode2",menuCode2==null?"":menuCode2);
		model.addAttribute("caseName","");
		if(StringUtils.isNotEmpty(caseid)) {
			CaseManage cm = caseManageService.findByCaseUuid(caseid);
			if(cm!=null) {
				model.addAttribute("caseName",cm.getCase_name());
			}
		}
		return "home";
	}
	
	/**
	 * 到首页
	 * @param model
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping("/home2")
	public String home2(ModelMap model,String menuCode,String caseid) throws ParseException {
		LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		// 查询用户的角色
		fillLoginUserRoleName(loginUser);
		request.getSession().setAttribute("loginUser", loginUser.getPlatManager());
		// 设置登录用户的菜单权限
		model.addAttribute("menuCode",menuCode==null?"":menuCode);
		model.addAttribute("caseid",caseid==null?"":caseid);
		return "home2";
	}
	@RequestMapping("/")
	public String index(ModelMap model) throws ParseException {
		LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		request.getSession().setAttribute("loginUser", loginUser.getPlatManager());
		setLoginUserSessionMenu(loginUser);
		return "index";
	}
	@RequestMapping("/main")
	public String main(ModelMap model) throws ParseException {
		return "main";
	}
	
	private void fillLoginUserRoleName(LoginUser loginUser) {
		List<PlatRoleUser> platRoleUserList = platRoleUserService.findByUserId(loginUser.getPlatManager().getId());
		if (platRoleUserList != null && !platRoleUserList.isEmpty()) {
			PlatRole platRole = platRoleService.findOne(platRoleUserList.get(0).getRoleId());
			if (platRole != null) {
				loginUser.getPlatManager().setRoleName(platRole.getRoleName());
			}
		}
	}

	private void setLoginUserSessionMenu(LoginUser loginUser) {
		// 通过userId查询菜单权限
		List<MenuInfo> menuInfoList = menuInfoService.findByUserId(loginUser.getPlatManager().getId());
		
		// 整理出菜单层级（二级）
		List<MenuInfo> firstLevelMenuList = new LinkedList<MenuInfo>();
		Map<String, List<MenuInfo>> secondLevelMenuMap = new LinkedHashMap<String, List<MenuInfo>>();
		Map<String, List<MenuInfo>> thirdLevelMenuMap = new LinkedHashMap<String, List<MenuInfo>>();
		Map<String, String> parentMenuCodeMap = new HashMap<String,String>();
		for (MenuInfo menuInfo: menuInfoList) {
			if (menuInfo.getMenuLevel() == 1) {
				firstLevelMenuList.add(menuInfo);
			} else if (menuInfo.getMenuLevel() == 2) {
				List<MenuInfo> secondLevelMenuList = secondLevelMenuMap.get(menuInfo.getMenuParentId().toString());
				if (secondLevelMenuList == null) {
					secondLevelMenuList = new LinkedList<MenuInfo>();
					secondLevelMenuList.add(menuInfo);
				} else {
					secondLevelMenuList.add(menuInfo);
				}
				secondLevelMenuMap.put(menuInfo.getMenuParentId().toString(), secondLevelMenuList);
			} else if (menuInfo.getMenuLevel() == 3) {
				List<MenuInfo> thirdLevelMenuList = thirdLevelMenuMap.get(menuInfo.getMenuParentId().toString());
				if (thirdLevelMenuList == null) {
					thirdLevelMenuList = new LinkedList<MenuInfo>();
					thirdLevelMenuList.add(menuInfo);
				} else {
					thirdLevelMenuList.add(menuInfo);
				}
				thirdLevelMenuMap.put(menuInfo.getMenuParentId().toString(), thirdLevelMenuList);
			}
			
			String menuCode = menuInfo.getMenuCode();
			String parentMenuCode = getParentMenuCode(menuInfoList, menuInfo.getMenuParentId());
			if(org.apache.commons.lang3.StringUtils.isNotEmpty(parentMenuCode)){
				parentMenuCodeMap.put(menuCode, parentMenuCode);
			}
		}
		
		
		request.getSession().setAttribute("firstLevelMenuList", firstLevelMenuList);
		request.getSession().setAttribute("secondLevelMenuMap", secondLevelMenuMap);
		request.getSession().setAttribute("thirdLevelMenuMap", thirdLevelMenuMap);
		request.getSession().setAttribute("parentMenuCodeMap", parentMenuCodeMap);
	}

	private String getParentMenuCode(List<MenuInfo> list,int pid) {
		String menuCode="";
		for(MenuInfo m:list) {
			if(m.getMenuId()==pid) {
				menuCode = m.getMenuCode();
				break;
			}
		}
		return menuCode;
	}

	@RequestMapping(value = "/login/sysOutLogin", method = RequestMethod.POST)
	public void sysOutLogin(ModelMap model, HttpServletResponse response,
			@RequestParam(required = true) String companyId) {
		try {
			response.setHeader("ContentType", "text/json");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			/* String postUrl = outPath+"login/sysOutLogin.action"; */
			Long timestaLong = System.currentTimeMillis() / 1000;
			String timesStr = String.valueOf(timestaLong);
			MD5 md5 = new MD5();
			String sign = md5.encrypt(SECRET + companyId + timesStr);
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("_clientType", "wap");
			paramMap.put("sign", sign);
			paramMap.put("timestamps", timestaLong);
			paramMap.put("companyId", companyId);
			Gson gson = new Gson();
			response.getWriter().write(gson.toJson(paramMap));
			response.getWriter().flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 设置左侧菜单body 折叠样式在session中存放、删除
	 * 
	 * @param request
	 * @param operation
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/setSessionSidebarCollapse", method = RequestMethod.POST)
	public Object setSessionSidebarCollapse(HttpSession session, String operation) {
		if (StringUtils.isNotEmpty(operation) && operation.equals("addClass")) {
			session.setAttribute("sidebar-collapse", "1");
		} else {
			session.removeAttribute("sidebar-collapse");
		}
		return SUCCESS();
	}
}
